package com.techysky.util;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.util.ClassUtils;

import com.mysql.jdbc.Driver;
import com.techysky.vo.DataBase;

public class DBUtil implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Log log=LogFactory.getLog(DBUtil.class);
	private static  JdbcTemplate template;

	/**
	 * 加载数据库驱动
	 * @param driver
	 * @return
	 */
	public static boolean loadDriver(String driver) {
		boolean result=true;
		try {
			if(!isLoaded(driver)) 
				Class.forName(driver);
		} catch (ClassNotFoundException e) {
			result=false;
			log.info(e);
		}
		return result;
	}
	
	/**
	 * 
	 * @param driver
	 * @param url
	 * @param userName
	 * @param password
	 * @return
	 */
	public static  Connection getConnection(DataBase db) {
		Connection con=null;
		if(loadDriver(db.getDriver())) {
			try {
				con=DriverManager.getConnection(db.getUrl(), db.getUserName(), db.getPassword());
			} catch (SQLException e) {
				log.info(e);
			}
		}
		return con;
	}
	
	/**
	 * 
	 * @param conn
	 * @param sql
	 * @return
	 */
	public static  int executeUpdate(Connection conn,String sql) {
		int result=0;
		try(PreparedStatement ps=conn.prepareStatement(sql)){
			return ps.executeUpdate();
		}catch (SQLException e) {
			log.info(e);
		}
		return result;
	}
	
	public static ResultSet getResult(Connection conn,String sql) {
		try(PreparedStatement ps = conn.prepareStatement(sql);ResultSet rs= ps.executeQuery();){
			return rs;
		}catch(SQLException e) {
			log.error(e);
		}
		return null;
	}

	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static  boolean isLoaded(String className) {
		boolean result=false;
		try {
			Field field=ClassLoader.class.getDeclaredField("classes");
			field.setAccessible(true);
			List<Class<?>> classes = (ArrayList)field.get(ClassLoader.getSystemClassLoader());
			for (Class<?> cla : classes) {
				if(ClassUtils.matchesTypeName(cla, className)) {
					result=true;
					break;
				}
			}
		} catch (Exception e) {
			log.info(e);
		}
		return result;
	}
	
	
	public static  JdbcTemplate jdbcTemplate(DataBase db) {
		DataSource ds;
		try {
			ds = new SimpleDriverDataSource((Driver) Class.forName(db.getDriver()).newInstance(), db.getUrl(), db.getUserName(), db.getPassword());
			template = new JdbcTemplate(ds);
		} catch (Exception e) {
			Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, "fail", e);
		} 
		return template;
	}
	
	

}
